﻿using System;
using System.Net;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace CommonUtils
{
    public class WebSocketServerSession : WebSocketBehavior
    {
        public Action<Exception, WebSocketServerSession> ErrorEvents;
        public Action<WebSocketServerSession> ConnectEvents;
        public Action<MessageEventArgs, WebSocketServerSession> ReceiveEvents;
        public Action<WebSocketServerSession> DisconnectEvents;

        public IPEndPoint ServerEndPoint { get; private set; }
        public IPEndPoint ClientEndPoint { get; private set; }

        protected override void OnError(ErrorEventArgs e)
        {
            LogUtil.PrintInfo("WebSocket服务端({0})会话{1}异常! ", ServerEndPoint, ClientEndPoint);
            ErrorEvents?.Invoke(e.Exception, this);
        }

        protected override void OnOpen()
        {
            ServerEndPoint = Context.ServerEndPoint;
            ClientEndPoint = Context.UserEndPoint;
            LogUtil.PrintInfo("WebSocket服务端({0})会话{1}已连接! ", ServerEndPoint, ClientEndPoint);
            ConnectEvents?.Invoke(this);
        }

        protected override void OnMessage(MessageEventArgs args)
        {
            LogUtil.PrintInfo("WebSocket服务端({0})会话{1}收到消息，长度{2}", ServerEndPoint, ClientEndPoint, args.Data.Length);
            ReceiveEvents?.Invoke(args, this);
        }

        protected override void OnClose(CloseEventArgs e)
        {
            LogUtil.PrintInfo("WebSocket服务端({0})会话{1}关闭! ", ServerEndPoint, ClientEndPoint);
            DisconnectEvents?.Invoke(this);
        }

        public new void Send(string data)
        {
            LogUtil.PrintInfo("WebSocket服务端({0})会话({1})发送消息，长度{2}! ", ServerEndPoint, ClientEndPoint, data.Length);
            base.Send(data);
        }

        public new void Send(byte[] data)
        {
            LogUtil.PrintInfo("WebSocket服务端({0})会话({1})发送字节，长度{2}! ", ServerEndPoint, ClientEndPoint, data.Length);
            base.Send(data);
        }
    }
}
